package com.ucpaas.sms.action.atuoAndBalckTemplate;

import com.alibaba.fastjson.JSON;
import com.jsmsframework.audit.dto.JsmsAutoTemplateDTO;
import com.jsmsframework.audit.dto.JsmsBalckTemplateDTO;
import com.jsmsframework.audit.entity.JsmsAutoTemplate;
import com.jsmsframework.audit.service.JsmsAutoBlackTemplateService;
import com.jsmsframework.audit.service.JsmsAutoTemplateService;
import com.jsmsframework.common.constant.SysConstant;
import com.jsmsframework.common.dto.JsmsPage;
import com.jsmsframework.common.dto.R;
import com.jsmsframework.common.dto.ResultVO;
import com.jsmsframework.common.entity.JsmsParam;
import com.jsmsframework.common.enums.WebId;
import com.jsmsframework.common.enums.balckAndWhiteTemplate.AutoTemplateStatus;
import com.jsmsframework.common.enums.balckAndWhiteTemplate.AutoTemplateSubmitType;
import com.jsmsframework.common.enums.balckAndWhiteTemplate.AutoTemplateType;
import com.jsmsframework.common.enums.balckAndWhiteTemplate.TemplateLevel;
import com.jsmsframework.common.service.JsmsParamService;
import com.jsmsframework.common.util.BeanUtil;
import com.jsmsframework.common.util.JsonUtil;
import com.jsmsframework.user.audit.service.JsmsUserAutoTemplateService;
import com.jsmsframework.user.entity.JsmsAccount;
import com.jsmsframework.user.entity.JsmsAgentInfo;
import com.jsmsframework.user.entity.JsmsUser;
import com.jsmsframework.user.service.JsmsAccountService;
import com.jsmsframework.user.service.JsmsAgentInfoService;
import com.jsmsframework.user.service.JsmsUserService;
import com.ucpaas.sms.action.BaseAction;
import com.ucpaas.sms.constant.LogConstant;
import com.ucpaas.sms.enums.LogEnum;
import com.ucpaas.sms.model.Excel;
import com.ucpaas.sms.service.LogService;
import com.ucpaas.sms.util.CommonUtil;
import com.ucpaas.sms.util.ConfigUtils;
import com.ucpaas.sms.util.UpaasHtmlUtils;
import com.ucpaas.sms.util.file.ExcelUtils;
import com.ucpaas.sms.util.file.FileUtils;
import com.ucpaas.sms.util.rest.utils.DateUtil;
import com.ucpaas.sms.util.web.AuthorityUtils;
import com.ucpaas.sms.util.web.StrutsUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Don on 2017/12/6.
 */

/**
 * 短信审核
 */
@Controller
@Scope("prototype")
@Results({ //\WEB-INF\content\balckAndWhiteTemplate list.jsp
        @Result(name = "autoTemplateQuery", location = "/WEB-INF/content/balckAndWhiteTemplate/auto/list.jsp"),
        @Result(name = "autoTemplateWaitQuery", location = "/WEB-INF/content/balckAndWhiteTemplate/auto/waitlist.jsp"),
        @Result(name = "autoTemplateAdd", location = "/WEB-INF/content/balckAndWhiteTemplate/auto/add.jsp"),
        @Result(name = "generalautoTemplateAdd", location = "/WEB-INF/content/balckAndWhiteTemplate/auto/addGeneral.jsp"),
        @Result(name = "templateAdd", location = "/WEB-INF/content/balckAndWhiteTemplate/auto/templateAdd.jsp"),
        @Result(name = "autoTemplateEdit", location = "/WEB-INF/content/balckAndWhiteTemplate/auto/edit.jsp")
       })
public class AutoTemplateAction extends BaseAction {
    private static final long serialVersionUID = 247987432825275374L;

    private static Logger logger = LoggerFactory.getLogger(BalckTemplateAction.class);

    @Autowired
    private JsmsAccountService jsmsAccountService;

    @Autowired
    private JsmsAutoTemplateService jsmsAutoTemplateService;

    @Autowired
    private JsmsUserService jsmsUserService;

    @Autowired
    private JsmsUserAutoTemplateService jsmsUserAutoTemplateService;

    @Autowired
    private LogService logService;

    @Autowired
    private JsmsAutoBlackTemplateService jsmsAutoBlackTemplateService;
    @Autowired
    private JsmsParamService jsmsParamService;
    @Autowired
    private JsmsAgentInfoService jsmsAgentInfoService;

    private File upload;
    private String uploadFileName;
    private String uploadContentType;

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }




    /**
     * 智能模板管理--已审核
     *
     * @return 返回页面
     */
    @Action("/autoTemplate/autoTemplate/query")
    public String autoTemplateQuery() {
        Map<String, String> params = StrutsUtils.getFormData();
        Map<String, Object> objectMap = new HashMap<>();

        Object obj = new Object();
        // 审核状态
        obj = params.get("state");
        if(obj==null){
            objectMap.put("state",99);
        }
        if (obj != null) {
            objectMap.put("state", obj);
        }
        // 模板属性
        obj = params.get("smsType");
        if (obj != null) {
            objectMap.put("smsType", obj);
        }
        // 模板类型
        obj = params.get("templateType");
        if (obj != null) {
            objectMap.put("templateType", obj);
        }
        // 模版ID
        obj = params.get("templateId");
        if (obj != null) {
            objectMap.put("templateId", obj);
        }
        // 短信签名
        obj = params.get("sign");
        if (obj != null) {
            objectMap.put("sign", obj);
        }
        // 模版内容
        obj = params.get("content");
        if (obj != null) {
            objectMap.put("content", obj);
        }
        // 用户帐号
        obj = params.get("clientId");
        if (obj != null) {
            objectMap.put("clientId", obj);
        }
        // 提交来源
        obj = params.get("submitType");
        if (obj != null) {
            objectMap.put("submitType", obj);
        }
        // 创建人
        obj = params.get("userName");
        if (obj != null) {
            objectMap.put("userName", obj);
        }
        // 审核人
        obj = params.get("adminName");
        if (obj != null) {
            objectMap.put("adminName", obj);
        }
        //模板级别
        obj = params.get("templateLevel");
        if (obj != null) {
            objectMap.put("templateLevel", obj);
        }
        //匹配次数
        obj = params.get("minNum");
        if (obj != null) {
            objectMap.put("minNum", obj);
        }
        obj = params.get("maxNum");
        if (obj != null) {
            objectMap.put("maxNum", obj);
        }

        // 更新时间：开始时间
        DateTime dt = DateTime.now();
        String startTime = Objects.toString(params.get("startTime"), "");
        String endTime = Objects.toString(params.get("endTime"), "");
        if (StringUtils.isNotBlank(startTime)) {
            objectMap.put("startTime", startTime);
        }else{

            startTime = DateUtil.dateToStr(DateUtil.getDateFromToday(-30),DateUtil.YMR_SLASH)+" 00:00:00";
            objectMap.put("startTime", startTime);
        }

        // 更新时间：结束时间
        if (StringUtils.isNotBlank(endTime)) {
            objectMap.put("endTime", endTime);
        }else {
            endTime=DateUtil.dateToStr(DateUtil.getDateFromToday(0),DateUtil.YMR_SLASH)+" 23:59:59";
          //  endTime = dt.plusMinutes(1).toString("yyyy-MM-dd HH:mm:ss");
            objectMap.put("endTime", endTime);
        }

        // 用于页面回显"更新时间"
        StrutsUtils.setAttribute("startTime", startTime);
        StrutsUtils.setAttribute("endTime", endTime);
        StrutsUtils.setAttribute("clientIdHidden", Objects.toString(params.get("clientId"), ""));

        JsmsPage<JsmsAutoTemplate> jsmsPage = CommonUtil.initJsmsPage(params);
        jsmsPage.setParams(objectMap);
        jsmsPage.setOrderByClause("a.update_time DESC");

        JsmsPage queryPage = jsmsUserAutoTemplateService.findListOfAutoTemplate(jsmsPage, WebId.短信调度系统.getValue());
        page = CommonUtil.converterJsmsPage2PageContainer(queryPage);
        return "autoTemplateQuery";
    }

    /**
     * 智能模板管理--已审核 --> 导出
     *
     * @return 返回页面
     */
    @Action("/autoTemplate/autoTemplate/export")
    public void autoTemplateExport() {
        Map<String, String> params = StrutsUtils.getFormData();

        Object obj = new Object();
//		objectMap.putAll(params);
        // 审核状态
        obj = params.get("state");
        if(obj==null){
            params.put("state","99");
        }

        // 更新时间：开始时间
        if (StringUtils.isBlank(params.get("startTime"))) {
            String startTime = DateUtil.dateToStr(DateUtil.getDateFromToday(-30),DateUtil.YMR_SLASH)+" 00:00:00";
            params.put("startTime", startTime);
        }
        // 更新时间：结束时间
        if (StringUtils.isBlank(params.get("endTime"))) {
            DateTime dt = DateTime.now();
            String endTime = dt.toString("yyyy-MM-dd HH:mm:ss");
            params.put("endTime", endTime);
        }

        StringBuffer filePath = new StringBuffer(ConfigUtils.save_path);
        if(!ConfigUtils.save_path.endsWith("/")){
            filePath.append("/");
        }
        filePath.append("智能模板已审核记录")
                .append(".xls")
                .append("$$$")
                .append(UUID.randomUUID());
        Excel excel = new Excel();
        excel.setFilePath(filePath.toString());
        excel.setTitle("智能模板已审核记录");

        StringBuffer buffer = new StringBuffer();
        buffer.append("查询条件：");
        String condition = null;
        condition = params.get("_state");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  审核状态：");
            buffer.append(condition);
            buffer.append(";");
        }

        condition = params.get("_smsType");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  模板属性：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("_");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  模板属性：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("_templateType");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  模板类型：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("templateId");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  模板ID：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("sign");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  签名：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("content");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  模板内容：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("clientId");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  用户账号：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("_submitType");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  提交来源：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("userName");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  创建者：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("adminName");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  审核人：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("startTime");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  更新时间(开始)：");
            buffer.append(condition);
            buffer.append(";");
        }
        condition = params.get("endTime");
        if (StringUtils.isNoneBlank(condition)) {
            buffer.append("  更新时间(结束)：");
            buffer.append(condition);
            buffer.append(";");
        }

        excel.addRemark(buffer.toString());

        excel.addHeader(20, "模板级别", "templateLevelStr");
        excel.addHeader(20, "模板ID", "templateId");
        excel.addHeader(20, "用户账号", "clientId");
        excel.addHeader(20, "模板属性", "smsTypeStr");
        excel.addHeader(20, "模板类型", "templateTypeStr");
        excel.addHeader(20, "模板内容", "content");
        excel.addHeader(20, "短信签名", "sign");
        excel.addHeader(20, "提交来源", "submitTypeStr");
        excel.addHeader(20, "创建者", "userName");
        excel.addHeader(20, "创建时间", "createTimeStr");
        excel.addHeader(20, "审核状态", "stateStr");
        excel.addHeader(20, "原因", "remark");
        excel.addHeader(20, "审核人", "adminName");
        excel.addHeader(20, "更新时间", "updateTimeStr");
        excel.addHeader(20, "匹配次数", "matchAmount");
        excel.addHeader(20, "最近匹配数", "latelyMatchAmount");
        excel.addHeader(20, "最近匹配日期", "latelyMatchDateStr");

        JsmsPage<JsmsAutoTemplate> jsmsPage = CommonUtil.initJsmsPage(params);
        jsmsPage.setOrderByClause("a.update_time DESC");
        jsmsPage.setRows(Integer.valueOf(ConfigUtils.max_export_excel_num) + 1);

        ResultVO resultVO = null;
        try {
            jsmsAutoTemplateService.findList(jsmsPage);
            List<JsmsAutoTemplateDTO> list = new ArrayList<>();
            List result = new ArrayList();
            for (Object temp : jsmsPage.getData()) {
                JsmsAutoTemplateDTO jsmsAutoTemplateDTO = new JsmsAutoTemplateDTO();
                BeanUtils.copyProperties(temp , jsmsAutoTemplateDTO);
                JsmsUser jsmsUser = jsmsUserService.getById(String.valueOf(jsmsAutoTemplateDTO.getAdminId()));
                if(jsmsUser != null){
                    jsmsAutoTemplateDTO.setAdminName(jsmsUser.getRealname());
                }
//                JsmsUser jsmsUser1 = jsmsUserService.getById(jsmsAutoTemplateDTO.getUserId());
//                if(jsmsUser1 != null){
//                    jsmsAutoTemplateDTO.setUserName(jsmsUser1.getRealname());
//                }
                if(StringUtils.isBlank(jsmsAutoTemplateDTO.getSign())){
                    jsmsAutoTemplateDTO.setSign("*");
                }
                if(StringUtils.isBlank(jsmsAutoTemplateDTO.getRemark())){
                    jsmsAutoTemplateDTO.setRemark("-");
                }
               JsmsAccount jsmsAccount=new JsmsAccount();
                if(jsmsAutoTemplateDTO.getSubmitType().equals(AutoTemplateSubmitType.客户提交.getValue())){
                    jsmsAccount = jsmsAccountService.getByClientId(String.valueOf(jsmsAutoTemplateDTO.getUserId()));
                    if(jsmsAccount!=null){
                        jsmsAutoTemplateDTO.setUserName(jsmsAccount.getName());
                    }
                }else if(jsmsAutoTemplateDTO.getSubmitType().equals(AutoTemplateSubmitType.代理商提交.getValue())){
                    JsmsAgentInfo jsmsAgentInfo = jsmsAgentInfoService.getByAgentId(Integer.parseInt(String.valueOf(jsmsAutoTemplateDTO.getUserId())));
                    if(jsmsAgentInfo!=null){
                        jsmsAutoTemplateDTO.setUserName(jsmsAgentInfo.getAgentName());
                    }
                }else if(jsmsAutoTemplateDTO.getSubmitType().equals(AutoTemplateSubmitType.平台提交.getValue())){
                    jsmsUser = jsmsUserService.getById(jsmsAutoTemplateDTO.getUserId());
                    if(jsmsUser != null){
                        jsmsAutoTemplateDTO.setUserName(jsmsUser.getRealname());
                    }
                }


                Map<String, String> describe = org.apache.commons.beanutils.BeanUtils.describe(jsmsAutoTemplateDTO);
                result.add(describe);
            }

            if (result == null || result.size() <= 0){
                resultVO = ResultVO.failure("没有数据！先不导出了  ^_^");
            }else if (result.size() > Integer.valueOf(ConfigUtils.max_export_excel_num)){
                resultVO =  ResultVO.failure("数据量超过"+ConfigUtils.max_export_excel_num+"，请缩小范围后再导出吧  ^_^");
            }

            /* 合计需要添加合计方法
            page = (JsmsPage) this.getClass().getMethod(queryMethod + "Total",page.getClass()).invoke(this, page);
            result.add(BeanUtils.describe(page.getTotalOtherData().get("totalLine")));*/
            excel.setDataList(result);
            if (ExcelUtils.exportExcel(excel)) {
                resultVO = ResultVO.successDefault();
                resultVO.setMsg("报表生成成功");
                resultVO.setData(excel.getFilePath());
            }
        } catch (Exception e) {
//			logg.error("生成报表失败", e);
            e.printStackTrace();
        }
        StrutsUtils.renderJson(resultVO);
    }



    /**
     * 智能模板管理--待审核
     *
     * @return 返回页面
     */
    @Action("/autoTemplate/autoTemplate/waitquery")
    public String autoTemplateWaitQuery() {
        Map<String, String> params = StrutsUtils.getFormData();
        Map<String, Object> objectMap = new HashMap<>();

        // 模版ID
        Object obj = new Object();

        objectMap.put("state","0"); //待审核
        obj = params.get("templateId");
        if (obj != null) {
            objectMap.put("templateId", obj);
        }

        // 用户帐号
        obj = params.get("clientId");
        if (obj != null) {
            objectMap.put("clientId", obj);
        }
        // 模板属性
        obj = params.get("smsType");
        if (obj != null) {
            objectMap.put("smsType", obj);
        }
        // 模板类型
        obj = params.get("templateType");
        if (obj != null) {
            objectMap.put("templateType", obj);
        }
        // 模版内容
        obj = params.get("content");
        if (obj != null) {
            objectMap.put("content", obj);
        }
        // 提交来源
        obj = params.get("submitType");
        if (obj != null) {
            objectMap.put("submitType", obj);
        }

        // 短信签名
        obj = params.get("sign");
        if (obj != null) {
            objectMap.put("sign", obj);
        }
        // 创建人
        obj = params.get("userName");
        if (obj != null) {
            objectMap.put("userName", obj);
        }
        DateTime dt = DateTime.now();
        // 创建时间：开始时间
        String startTime = Objects.toString(params.get("startTime"), "");
        String endTime = Objects.toString(params.get("endTime"), "");
        if (StringUtils.isNotBlank(startTime)) {
            objectMap.put("createStartTime", startTime);
        }else{

            startTime = DateUtil.dateToStr(DateUtil.getDateFromToday(-30),DateUtil.YMR_SLASH)+" 00:00:00";
            objectMap.put("createStartTime", startTime);
        }

        // 创建时间：结束时间
        if (StringUtils.isNotBlank(endTime)) {
            objectMap.put("createEndTime", endTime);
        }else {
            endTime=DateUtil.dateToStr(DateUtil.getDateFromToday(0),DateUtil.YMR_SLASH)+" 23:59:59";
          //  endTime = dt.toString("yyyy-MM-dd HH:mm:ss");
            objectMap.put("createEndTime", endTime);
        }

        // 用于页面回显"创建时间"
        StrutsUtils.setAttribute("startTime", startTime);
        StrutsUtils.setAttribute("endTime", endTime);
        StrutsUtils.setAttribute("clientIdHidden", Objects.toString(params.get("clientId"), ""));

        JsmsPage<JsmsAutoTemplate> jsmsPage = CommonUtil.initJsmsPage(params);
        jsmsPage.setParams(objectMap);

        obj = params.get("querydesc");
        if(obj==null){
            obj=2;
        }
        if("1".equals(obj.toString())){
            jsmsPage.setOrderByClause("a.create_time DESC");
        }else if("2".equals(obj.toString())){
            jsmsPage.setOrderByClause("a.match_amount DESC,a.create_time DESC");
        }

        //	StrutsUtils.setAttribute("querydesc", obj);

        JsmsPage queryPage = jsmsUserAutoTemplateService.findListOfAutoTemplate(jsmsPage,WebId.短信调度系统.getValue());
		/*List<JsmsAutoTemplateDTO> list = new ArrayList<>();
		for (Object temp : queryPage.getData()) {
			JsmsAutoTemplateDTO jsmsAutoTemplateDTO = new JsmsAutoTemplateDTO();
			BeanUtils.copyProperties(temp , jsmsAutoTemplateDTO);
			JsmsUser jsmsUser = jsmsUserService.getById(String.valueOf(jsmsAutoTemplateDTO.getAdminId()));
			if(jsmsUser != null){
				jsmsAutoTemplateDTO.setAdminName(jsmsUser.getRealname());
			}
			JsmsUser jsmsUser1 = jsmsUserService.getById(jsmsAutoTemplateDTO.getUserId());
			if(jsmsUser1 != null){
				jsmsAutoTemplateDTO.setUserName(jsmsUser1.getRealname());
			}

			list.add(jsmsAutoTemplateDTO);
		}
		queryPage.setData(list);*/
        page = CommonUtil.converterJsmsPage2PageContainer(queryPage);
        return "autoTemplateWaitQuery";
    }

    /**
     * 查询所有的客户
     */
    @Action("/autoTemplate/autoTemplate/accounts")
    public void getAccounts() {
        List<JsmsAccount> data = new ArrayList<>();
        String clientId = StrutsUtils.getParameterTrim("clientId");
        String type = StrutsUtils.getParameterTrim("type");
        if("exist".equals(type)){
            data =  jsmsAccountService.findAllListExist(clientId,"-6");
        }else{
            data = jsmsAccountService.findAllList(clientId);
        }
        StrutsUtils.renderJson(data);
    }



    /**
     * 查询客户模版列表
     */
    @Action("/autoTemplate/autoTemplate/list")
    public void autoTemplateList() {
        Map<String, String> params = StrutsUtils.getFormData();

        JsmsPage<JsmsAutoTemplate> page = new JsmsPage<>();
        Object obj = params.get("rows");
        if (obj != null) {
            page.setRows(Integer.parseInt(obj.toString()));
        }

        obj = params.get("page");
        if (obj != null) {
            page.setPage(Integer.parseInt(obj.toString()));
        }

        Map<String, Object> objectMap = new HashMap<>();

        // 模版ID
        obj = params.get("templateId");
        if (obj != null) {
            objectMap.put("templateId", obj);
        }

        // 用户帐号
        obj = params.get("clientId");
        if (obj != null) {
            objectMap.put("clientId", obj);
        }

        // 短信类型
        obj = params.get("smsType");
        if (obj != null) {
            objectMap.put("smsType", obj);
        }

        // 模版内容
        obj = params.get("content");
        if (obj != null) {
            objectMap.put("content", obj);
        }

        // 短信签名
        obj = params.get("sign");
        if (obj != null) {
            objectMap.put("sign", obj);
        }

        // 审核人
        obj = params.get("adminName");
        if (obj != null) {
            objectMap.put("adminName", obj);
        }

        // 审核人
        obj = params.get("startTime");
        if (obj != null) {
            objectMap.put("startTime", obj);
        }

        // 审核人
        obj = params.get("endTime");
        if (obj != null) {
            objectMap.put("endTime", obj);
        }

        page.setParams(objectMap);
        page.setOrderByClause("a.create_time DESC");
        StrutsUtils.renderJson(jsmsAutoTemplateService.findList(page));
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
    /**
     * 查询所有的客户
     */
    @Action("/autoTemplate/autoTemplate/add")
    public String autoTemplateAdd() {
        Map<String, String> params = StrutsUtils.getFormData();
        if(params.get("templateId")!=null){
            Integer templateId=Integer.valueOf(params.get("templateId"));
            JsmsAutoTemplate auto=jsmsAutoTemplateService.getByTemplateId(templateId);
            Map<String,Object> data1=new HashedMap();

            data1.put("content", UpaasHtmlUtils.Html2Text(auto.getContent()==null?"":auto.getContent().trim()));
            data1.put("sign",auto.getSign());
            data1.put("smsContent",UpaasHtmlUtils.Html2Text(auto.getSmsContent()==null?"":auto.getSmsContent().trim()));
            data1.put("smsType",replaceBlank(String.valueOf(auto.getSmsType())));
            data1.put("submitType",replaceBlank(String.valueOf(auto.getSubmitType())));
            data1.put("templateType",replaceBlank(String.valueOf(auto.getTemplateType())));
            data1.put("clientId",replaceBlank(auto.getClientId()));
            data1.put("templateId",replaceBlank(String.valueOf(auto.getTemplateId())));
            data1.put("state",replaceBlank(String.valueOf(auto.getState())));
            data=data1;
        }

        return "autoTemplateAdd";
    }
    /**
     * 新增,编辑,审批 用户智能模板
     */
    @Action("/autoTemplate/template/add")
    public String templateAdd() {
        Map<String, String> params = StrutsUtils.getFormData();
        if(params.get("templateId")!=null){
            Integer templateId=Integer.valueOf(params.get("templateId"));
            JsmsAutoTemplate auto=jsmsAutoTemplateService.getByTemplateId(templateId);
            Map<String,Object> data1=new HashedMap();
            data1=BeanUtil.beanToMap(auto,false);
            data1.put("content",UpaasHtmlUtils.Html2Text(auto.getContent().trim()));
            data1.put("sign",auto.getSign());
            data1.put("smsContent",UpaasHtmlUtils.Html2Text(auto.getSmsContent()==null?"":auto.getSmsContent().trim()));
            data1.put("smsType",replaceBlank(String.valueOf(auto.getSmsType())));
            data1.put("submitType",replaceBlank(String.valueOf(auto.getSubmitType())));
            data1.put("templateType",replaceBlank(String.valueOf(auto.getTemplateType())));
            data1.put("clientId",replaceBlank(auto.getClientId()));
            data1.put("templateId",replaceBlank(String.valueOf(auto.getTemplateId())));
            data1.put("state",replaceBlank(String.valueOf(auto.getState())));
            data1.put("remark",UpaasHtmlUtils.Html2Text(String.valueOf(auto.getRemark()==null?"":auto.getRemark().trim())));
            data=data1;
        }

        return "templateAdd";
    }

    /**
     * 新增,编辑,审批 通用智能模板
     */
    @Action("/autoTemplate/generalTemplate/add")
    public String generalTemplateAdd() {
        Map<String, String> params = StrutsUtils.getFormData();
        if(params.get("templateId")!=null){
            Integer templateId=Integer.valueOf(params.get("templateId"));
            JsmsAutoTemplate auto=jsmsAutoTemplateService.getByTemplateId(templateId);
            Map<String,Object> data1=new HashedMap();
            data1= BeanUtil.beanToMap(auto,false);
            data1.put("content",UpaasHtmlUtils.Html2Text(auto.getContent().trim()));
            data1.put("sign",auto.getSign());
            data1.put("smsContent",UpaasHtmlUtils.Html2Text(auto.getSmsContent()==null?"":auto.getSmsContent().trim()));
            data1.put("smsType",replaceBlank(String.valueOf(auto.getSmsType())));
            data1.put("submitType",replaceBlank(String.valueOf(auto.getSubmitType())));
            data1.put("templateType",replaceBlank(String.valueOf(auto.getTemplateType())));
            data1.put("clientId",replaceBlank(auto.getClientId()));
            data1.put("templateId",replaceBlank(String.valueOf(auto.getTemplateId())));
            data1.put("state",replaceBlank(String.valueOf(auto.getState())));
            data=data1;
        }

        return "generalautoTemplateAdd";
    }


    /**
     * 弃用
     */
    @Deprecated
    @Action("/smsaudit/autoTemplate/edit")
    public String autoTemplateEdit() {
        return "autoTemplateEdit";
    }


    /**
     * 新增or编辑智能模板审核
     */
    @Action("/autoTemplate/autoTemplate/save")
    public void autoTemplateSave() {
        Map<String, String> params = StrutsUtils.getFormData();

        boolean isMod = false;
        JsmsAutoTemplate template = new JsmsAutoTemplate();

        // 模版ID
        Object obj = params.get("templateId");
        if (obj != null) {
            isMod = true;
            template.setTemplateId(Integer.parseInt(obj.toString()));
        }

        //模板级别
        obj = params.get("templateLevel");
        if(obj != null){
            template.setTemplateLevel(Integer.valueOf(obj.toString()));
        }
        R r2=this.checkOverNum(template);
        if(Objects.equals(r2.getCode(),SysConstant.FAIL_CODE)){
            StrutsUtils.renderJson(r2);
        }else {
            // 用户帐号
            obj = params.get("clientId");
            if (obj != null) {
                template.setClientId(obj.toString());
            } else if (Objects.equals(template.getTemplateLevel(), TemplateLevel.全局级别.getValue())) {
                template.setClientId(SysConstant.ALL);
            }


            // 模版类型
            obj = params.get("templateType");
            if (obj != null) {
                template.setTemplateType(Integer.parseInt(obj.toString()));
            }

            // 短信类型
            obj = params.get("smsType");
            if (obj != null) {
                template.setSmsType(Integer.parseInt(obj.toString()));
            }/*else{
			StrutsUtils.renderJson(R.error("请选择短信类型"));
			return;
		}*/

            // 模版内容
            obj = params.get("content");
            if (obj != null) {
                template.setContent(obj.toString());
            }
            //审核状态
            obj = params.get("state");

            if (obj != null) {
                template.setState(Integer.valueOf(obj.toString()));
            }else if(Objects.equals(template.getTemplateLevel(),TemplateLevel.全局级别.getValue())){
                template.setState(AutoTemplateStatus.审核通过.getValue());
            }

            // 短信签名
            obj = params.get("sign");
            if (obj != null) {
                template.setSign(obj.toString());
            }else {
                template.setSign(null);
            }

            //不通过原因
            obj = params.get("remark");
            if (obj != null) {
                template.setRemark(obj.toString());
            }
            //提交类型
            obj = params.get("submitType");
            if (obj != null) {
                template.setSubmitType(Integer.valueOf(obj.toString()));
            }
            //删除标志
            boolean isSureDel = false;
            obj = params.get("isSureDel");
            if (obj != null) {
                isSureDel = Boolean.parseBoolean((String) obj);
            }
            // 审核人
            template.setAdminId(AuthorityUtils.getLoginUserId());

            R r;
            if (StringUtils.isBlank(template.getClientId()) /*|| jsmsAccountService.getByClientId(template.getClientId()) == null*/) {
                StrutsUtils.renderJson(R.error("用户账号不存在"));
            } else {
                if (isMod) {
                    logService.add(LogConstant.LogType.update, LogEnum.智能模板管理.getValue(), "短信审核-智能模版管理：审核模版", params, JsonUtil.toJson(template));
                    if (template.getState().equals(1) && Objects.equals(TemplateLevel.用户级别.getValue(),template.getTemplateLevel())) {
                        template.setRemark(" ");
                    }
                    template.setLatelyMatchAmount(0);
                    template.setLatelyMatchDate(null);
                    template.setMatchAmount(0);
                    template.setWebId(WebId.短信调度系统.getValue());
                    r = jsmsAutoTemplateService.modAutoTemplate(template, isSureDel);
                } else {
                    logService.add(LogConstant.LogType.add, LogEnum.智能模板管理.getValue(), "短信审核-智能模版管理：添加模版", params, JsonUtil.toJson(template));
                    if (template.getState() == null) {
                        template.setState(AutoTemplateStatus.审核通过.getValue());
                    }
                    template.setWebId(WebId.短信调度系统.getValue());
                    template.setUserId(String.valueOf(AuthorityUtils.getLoginUserId()));
                    template.setSubmitType(AutoTemplateSubmitType.平台提交.getValue());
                    if (isSureDel) {
                        r = jsmsAutoTemplateService.addAutoTemplate(template, isSureDel);
                    } else {
                        r = jsmsAutoTemplateService.addAutoTemplate(template);
                    }
                }

                StrutsUtils.renderJson(r);
            }
        }


    }


    /**
     * 查询是否超标添加全局模板
     * @param template
     * @return
     */
    private R checkOverNum(JsmsAutoTemplate template){
        //校验是否超标添加全局模板
        if(template.getTemplateId()==null && Objects.equals(template.getTemplateLevel(),TemplateLevel.全局级别.getValue())){
            List<JsmsParam> paramKey = jsmsParamService.getByParamKey(SysConstant.GLOBAL_TEMPLATE_NUMBER);
            if(paramKey != null && paramKey.size()>0){
                JsmsParam overparam = paramKey.get(0);
                BigDecimal overNum=new BigDecimal(overparam.getParamValue());
                Map<String,Object> param=new HashedMap();
                param.put("templateLevel",TemplateLevel.全局级别.getValue());
                int count=jsmsAutoTemplateService.count(param);
                if(BigDecimal.valueOf(count).compareTo(overNum)!=-1){
                    return	R.error("通用模板已达到最高限制数！");
                }
            }else{
                return  R.error("无全局模板参数");
            }
        }
        return  R.ok("通用模板可添加");

    }


    /**
     * 删除智能模板
     */
    @Action("/autoTemplate/autoTemplate/del")
    public void autoTemplateDel() {

        String templateIdStr = StrutsUtils.getParameterTrim("templateId");
        Integer templateId = null;
        // 模版ID
        if (StringUtils.isNotBlank(templateIdStr)) {
            templateId  = Integer.parseInt(templateIdStr);
        }

        if (templateId == null) {
            StrutsUtils.renderJson(R.error("模版ID不能为空"));
            return;
        }

        logService.add(LogConstant.LogType.update, LogEnum.智能模板管理.getValue(), "短信审核-智能模版管理：删除模版", templateId, templateId);
        R r = jsmsAutoTemplateService.delAutoTemplate(templateId);
        StrutsUtils.renderJson(r);
    }

    /**
     * 下载批量添加智能模板Excel
     */
    @Action("/autoTemplate/downloadExcelTemplate")
    public void downloadExcelTemplate() {
        String path = StrutsUtils.getRequest().getServletContext().getRealPath("/templateFile/批量添加智能模板.xls");
        FileUtils.download(path);
    }


    /**
     * 批量添加智能模板
     */
    @Action("/autoTemplate/addAutoTemplateBatch")
    public void importExcel() {

         R r=jsmsUserAutoTemplateService.addAutoTemplateBatch(upload, uploadContentType, AuthorityUtils.getLoginUserId().toString(), ConfigUtils.save_path,WebId.短信调度系统.getValue());
        // R r = jsmsAutoTemplateService.addAutoTemplateBatch(upload, uploadContentType, AuthorityUtils.getLoginUserId(), ConfigUtils.save_path);
        StrutsUtils.renderJson(r);
    }

    @Action("/autoTemplate/exportImportResult")
    public void exportError(){
        String filePath = ConfigUtils.save_path +"/import"+ "/批量添加智能模板结果-userid-" + AuthorityUtils.getLoginUserId()+".xls";
        File file = new File(filePath);
        if(file.exists()){
            FileUtils.download(filePath);
        }else{
            StrutsUtils.renderText("文件过期、不存在或者已经被管理员删除");
        }
    }

    @Action("/autoTemplate/getAccountSmsTypeByClientId")
    public void getAccountSmsTypeByClientId(){
        String clientId = StrutsUtils.getParameterTrim("clientId");
        JsmsAccount jsmsAccount = jsmsAccountService.getByClientId(clientId);
        String smsType = null;
        if(jsmsAccount != null)
            smsType = String.valueOf(jsmsAccount.getSmstype());

        StrutsUtils.renderJson(smsType);
    }


}